const { getSqlLiteData } = require('../../SqlLiteDB');

module.exports = function setMaterialRouter (router) {

    //查询物料信息
    router.get('/getMaterials', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.query['dataContent']);
            // 物料类型
            let mattype = dataContent.mattype;
            // 客户
            let wocusid = dataContent.wocusid;
            let SqlString = "SELECT * FROM pm_material U"
                + ` WHERE 1=1`
                + (mattype ? ` AND U.mattype ='${mattype}'` : '')
                + (wocusid ? ` AND U.wocusid ='${wocusid}'` : '')
                + " ORDER BY U.matcode";
            let procedures = await getSqlLiteData(SqlString);

            res.status(200).json({
                procedures,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });

    //修改或添加物料信息
    router.post('/updateMaterial', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.body['dataContent']);
            let { matcode, matname, mattype, wocusid } = dataContent.material;
            // let wocusid = dataContent.wocusid;
            // let name = dataContent.name;
            // let remark = dataContent.remark;
            // let user = dataContent.user;

            let SqlString = `REPLACE INTO pm_material(matcode, matname, mattype, wocusid) 
            VALUES ('${matcode}','${matname}', '${mattype}','${wocusid}')`;
            let result = await getSqlLiteData(SqlString);

            res.status(200).json({
                result,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });

    //删除物料
    router.post('/deleteMaterial', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.body['dataContent']);
            let matcode = dataContent.matcode;
            let wocusid = dataContent.wocusid;

            let SqlString = `DELETE FROM pm_material WHERE matcode ='${matcode}' AND wocusid ='${wocusid}'`;
            let result = await getSqlLiteData(SqlString);

            res.status(200).json({
                result,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });
};
